import router from '@/router/index'
import authUtil from '@/utils/authUtil'
import { toast } from '@/utils/common'
import { useAuthStore } from '@/stores/authStore'
import NProgress from 'nprogress'

interface menuListType {
    name: string
    path: string
    component: string | any
    alwaysShow: boolean
    meta: {
        title: string
        icon: string
    }
    children: Array<menuListType>
}

const modules = import.meta.glob('@/views/**/*.vue')
// console.log(modules)
// for( const path in modules){
//     const mode = modules[path]
//     console.log(path,mode) //  /src/views/order/refund.vue () => import("/src/views/order/refund.vue")
// }

const createDynamicRoutes = (
    parent = 'layout',
    parentPath = '/',
    menuList: Array<menuListType>
) => {
    for (const menu of menuList) {
        if (menu?.children?.length > 0) {
            menu.component = null
            if ('/' === parentPath) {
                menu.path = parentPath + menu.path
            } else {
                menu.path = parentPath + '/' + menu.path
            }
            createDynamicRoutes(menu.name, menu.path, menu.children)
        } else {
            menu.path = parentPath + '/' + menu.path
            menu.component = modules[`/src/views/${menu.component}.vue`]
            router.addRoute(parent, menu)
        }
    }
}

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const token = authUtil.getToken()
    // 如果没有登录, 则跳转到登录页
    if (!token && '/login' !== to.path) {
        toast('请登录', 'error')
        return next({ path: '/login' })
    }

    // 防止重复登录
    if (token && '/login' === to.path) {
        toast('请务重复登录', 'warning')
        return next({ path: from.path ? from.path : '/' })
    }

    // 登录后, 获取用户信息并保存到 pinia 中
    if (token) {
        const authStore = useAuthStore()
        await authStore.getUserInfo()
        if (authStore.getMarkDynamicRoutes) {
            // 修改标题
            document.title = (to.meta.title ? to.meta.title : '') + '- thresh'
            next()
        } else {
            authStore.setMarkDynamicRoutes()

            const routeList = authStore.getRouters
            createDynamicRoutes('layout', '/', routeList)

            for (const r of routeList) {
                router.addRoute('layout', r)
            }

            router.addRoute({
                path: '/:pathMatch(.*)',
                name: 'NotFound',
                component: () => import('@/views/404.vue')
            })
            next({ ...to, replace: true })
        }
    } else {
        next()
    }
})

router.afterEach(() => {
    NProgress.done()
})
